export default {
  namespaced:true,
  state:{
    ws:null,
    isConnected:false
  },
  mutations:{
    SET_WS(state,ws) {
      state.ws = ws
    },
    SET_IS_CONNECTED(state,isConnected) {
      state.isConnected = isConnected
    }
  },
  actions:{
    connect({state,commit,dispatch},obj) {
      if(!state.isConnected) {
        // console.log(obj,'obj.............')
        
        let ws = uni.connectSocket({
          url:obj.url,
          header:obj.headers,
          success: () => {
            console.log('webscoket 已连接')
            commit('SET_IS_CONNECTED',true)
            commit('SET_WS',ws)
            
          }
          
        })
        // console.log(ws.onOpen())
        // ws.onOpen(res => {
        //   console.log('webscoket 已连接')
        //   commit('SET_IS_CONNECTED',true)
        //   commit('SET_WS',ws)
        // })
        ws.onClose(() => {
          console.log('webScoket 已关闭')
          commit('SET_IS_CONNECTED',false)
          commit('SET_WS',null)
        })
        ws.onError((error) => {
          console.error('webscoket 错误',error)
        })
        ws.onMessage((res) => {
          console.log('收到消息',res.data)
        })
      }
     
    },
    close({commit}) {
      if(state.ws) {
        state.ws.close()
        commit('SET_IS_CONNECTED',false)
        commit('SET_WS',null)
        
      }
    }
  }
}